/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/

#include "kdata.h"
#include "kerror.h"
#include "kstream.h"
#include <string.h>

kDataBufferView::~kDataBufferView() {
	if (_data.ptr || _data.size) {
		throw kError(_T("Invalid data buffer operation!"));
	}
}
kDataBuffer::kDataBuffer() {
}
kDataBuffer::kDataBuffer(size_t size) {
	resize(size);
}
kDataBuffer::kDataBuffer(const kDataView& source) {
	replace(source);
}
kDataBuffer::kDataBuffer(kStream* stream) {
	size_t size = stream->getSize();
	resize(size);
	stream->read(getData());
}
kDataBuffer::~kDataBuffer() {
	if (_data.ptr) {
		free(_data.ptr);
		_data.ptr = 0;
		_data.size = 0;
	}
}

void kDataBuffer::resize(size_t size) {
	uint8_t* newptr = (uint8_t*)realloc(_data.ptr, size);
	if (newptr || !size) {
		_data.size = size;
		_data.ptr = newptr;
	} else {
		throw kError(_T("Memory allocation failed!"));
	}
}
void kDataBuffer::fill(uint8_t value, size_t offset, size_t length) const {
	if (offset < _data.size) {
		length = std::min(length, _data.size - offset);
		memset(_data.ptr + offset, value, length);
	}
}
void kDataBuffer::append(const kDataView& data) {
	size_t oldsize = _data.size;
	resize(_data.size + data.size);
	memcpy(_data.ptr + oldsize, data.ptr, data.size);
}
void kDataBuffer::replace(const kDataView& data) {
	resize(data.size);
	memcpy(_data.ptr, data.ptr, data.size);
}
